package com.example.demo.error;

public class StackOverFlowDemo2 {


    /**
     * 当两个对象相互引用，在调用toString方法时会产生这个异常，因为它们会循环调用toString方法; 因为当打印一个对象的时候，会先调用这个对象的toString()方法
     */
    static class Student {
        String name;
        Book book;

        public Student(String name) {
            this.name = name;
        }

        //循环调用toString方法
        @Override
        public String toString() {
            return "Student{" +
                    "name='" + name + '\'' +
                    ", book=" + book +
                    '}';
        }

    }

    static class Book {
        String isbn;
        Student student;

        public Book(String isbn, Student student) {
            this.isbn = isbn;
            this.student = student;
        }

        @Override
        public String toString() {
            return "Book{" +
                    "isbn='" + isbn + '\'' +
                    ", student=" + student +
                    '}';
        }
    }

    public static void main(String[] args) {
        Student student = new Student("zhang3");
        Book book = new Book("1111", student);
        student.book = book;
        System.out.println(book.toString());
    }

}
